package com.example.jwtdemo.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.jwtdemo.entity.User;
import com.example.jwtdemo.service.UserService;
import com.example.jwtdemo.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Woo_home
 * @create 2020/9/13 23:19
 */

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/user/login")
    public Map<String, Object> login(User user) {
        log.info("用户名：[{}]", user.getUsername());
        log.info("密码：[{}]", user.getPassword());
        Map<String, Object> map = new HashMap<>();
        try {
            user = userService.login(user);
            Map<String, String> payload = new HashMap<>();
            payload.put("id", user.getId());
            payload.put("username", user.getUsername());
            // 生成 JWT 的令牌
            String token = JwtUtil.generToken(payload);
            map.put("state", true);
            map.put("msg", "认证成功");
            map.put("token", token);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }


    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        // 处理自己业务逻辑
        String token = request.getHeader("token");
        DecodedJWT verify = JwtUtil.verify(token);
        log.info("用户 id：[{}]", verify.getClaim("id").asString());
        log.info("用户 username：[{}]", verify.getClaim("username").asString());
        map.put("state", true);
        map.put("msg", "请求成功！");
        return map;
    }
}
